package com.lx.listen;

import com.lx.entity.OrderDetail;
import com.lx.entity.Product;
import com.lx.service.OrderService;
import com.lx.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * 2025/9/21 11:49
 * author: 向远洋
 */
@Component
public class RedisExpiredListener implements MessageListener {
    //监听主题
    private  final PatternTopic topic = new PatternTopic("__keyevent@*__:expired");
    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String topic = new String(pattern);
        String msg = new String(message.getBody());
        if(msg.endsWith("orderPaying")) {
            System.out.println("收到key的过期，消息主题是："+ topic+",消息内容是："+msg);
            //将订单状态 -> 取消， order.getId() + "_" + order.getUserId() + "orderPaying"
            String orderPaying = msg.substring(0, msg.lastIndexOf("orderPaying"));
            String[] ids = orderPaying.split("_");
            int orderId = Integer.parseInt(ids[0]);
            if(orderService.getEasyOrderById(orderId).getIsPay() < 1) { //付款：1，退款2
                orderService.modifyOrderStatusById(orderId, -1);
            }
            int userId = Integer.parseInt(ids[1]);
            stringRedisTemplate.delete(userId + "orderCar");
            //订单取消要修改es和数据库商品数量
            List<OrderDetail> orderDetailList = orderService.getOrderDetailList(Collections.singletonList(orderId));
            for (OrderDetail orderDetail : orderDetailList) {
                //恢复es和数据库
                Product p = productService.getProductById(orderDetail.getProductId());
                p.setStock(p.getStock() + orderDetail.getQuantity());
                productService.updateProduct(p);
            }
        }
    }

    public Topic getTopic() {
        return topic;
    }
}
